package com.inspectortime.webapp.inspector;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.RealEstateAgent;
import com.inspectortime.domain.type.State;
import com.inspectortime.repository.Factory;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.SpringValidatorUtils;
import com.inspectortime.webapp.util.DomainUtils;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class EditReferringRealtorController extends SimpleFormController {

	private static Log log = LogFactory.getLog(EditReferringRealtorController.class);
	private Factory factory;

	public void setFactory(Factory factory) {
		this.factory = factory;
	}

	private Repository repository;

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("states", State.values());
		return data;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		RealEstateAgent realtor = null;
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		
		String id = request.getParameter("id");
		if (id != null && id.length() > 0) {
			realtor = repository.loadRealEstateAgent(id);
			//make sure realtor is associated with company to prevent url hacking
			if (!company.getReferringAgents().contains(realtor)) {
				throw new Exception("Agent not found");
			}
		//handle the auto-complete search field
		} else if (StringUtils.hasText(request.getParameter("selectedRealtorName"))) {
			realtor = DomainUtils.getExistingRealtorByAutoCompletionName(request.getParameter("selectedRealtorName"), 
																		 company.getReferringAgents());
			if (realtor == null) {
				//TODO: HANDLE THIS ERROR
				throw new Exception("Agent not found");
			}
			
		} else {
			realtor = factory.createRealEstateAgent();
		}
		return realtor;
	}
	
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception {
		SpringValidatorUtils.logValidationErrors(log, errors);
	}

	protected ModelAndView onSubmit(
			HttpServletRequest request,	HttpServletResponse response, Object command,	BindException errors)
			throws Exception {

		RealEstateAgent realtor = (RealEstateAgent) command;
		
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		if (!company.getReferringAgents().contains(realtor)) {
			realtor.save();
			company.getReferringAgents().add(realtor);
			company.save();				
		} else {
			realtor.save();
		}
		
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		return mv;
	}

}
